package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.commons.result.ResponseData;
import cn.cmm.base.framework.utils.*;
import cn.fl.preloan.condition.InsCompChnPolQueryCondition;
import cn.fl.preloan.dto.*;
import cn.fl.preloan.enums.PreloanResultCodeEnum;
import cn.fl.preloan.insurance.IInsCompChnPollService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.insurance.service.IInsCompChnPolService;
import cn.fl.insurance.vo.InsCompChnPolVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 渠道政策 控制层
 */
@Controller
@RequestMapping("/insurance/insCompChnPol")
public class InsCompChnPolController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsCompChnPolController.class);

    /**
     * InsCompChnPol 服务层BEAN
     */
    @Autowired
    private IInsCompChnPolService insCompChnPolService;

    @Autowired
    private IInsCompChnPollService insCompChnPollService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载InsCompChnPol列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompChnPol/insCompChnPolList");
        String chnCd = request.getParameter("chnCd");
        mav.addObject("chnCd", chnCd);
        String insCompId = request.getParameter("insCompId");
        mav.addObject("insCompId", insCompId);
        return mav;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDtlListPage.do", method = {RequestMethod.GET})
    public ModelAndView toDtlListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toDtlListPage", "加载InsCompChnPol详情页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompChnPol/insCompChnPolDtl");
        String chnCd = request.getParameter("chnCd");
        if (StringUtils.isNotEmpty(chnCd) && "2".equals(chnCd)) {
            mav.setViewName("insurance/insCompChnPol/insCompChnProcessDtl");
        }
        mav.addObject("chnCd", chnCd);
        String insCompId = request.getParameter("insCompId");
        mav.addObject("insCompId", insCompId);
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载InsCompChnPol Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompChnPol/insCompChnPolModify");
        //加载数据字典数据、传值等 ？
        List<KeyValueVO> insTypCdList = this.insCompChnPolService.searchInsTypCdList();
        List<KeyValueVO> prdTypCdList = this.insCompChnPolService.searchPrdTypCdList();
        mav.addObject("insTypCdList", insTypCdList);//险种种类
        mav.addObject("prdTypCdList", prdTypCdList);//产品类型

        String chnCd = request.getParameter("chnCd");
        if (StringUtils.isNotBlank(chnCd) && "1".equals(chnCd)) {
            List<KeyValueVO> rebNatCdList = this.insCompChnPolService.searchRebNatCdList();
            mav.addObject("rebNatCdList", rebNatCdList);//渠道返利性质
        }
        mav.addObject("chnCd", chnCd);
        String insCompId = request.getParameter("insCompId");
        mav.addObject("insCompId", insCompId);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载InsCompChnPol Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insCompChnPol/insCompChnPolModify");
        //加载数据字典数据、传值等 ？
        List<KeyValueVO> insTypCdList = this.insCompChnPolService.searchInsTypCdList();
        List<KeyValueVO> prdTypCdList = this.insCompChnPolService.searchPrdTypCdList();
        mav.addObject("insTypCdList", insTypCdList);//险种种类
        mav.addObject("prdTypCdList", prdTypCdList);//产品类型

        String chnCd = request.getParameter("chnCd");
        if (StringUtils.isNotBlank(chnCd) && "1".equals(chnCd)) {
            List<KeyValueVO> rebNatCdList = this.insCompChnPolService.searchRebNatCdList();
            mav.addObject("rebNatCdList", rebNatCdList);//渠道返利性质
        }
        mav.addObject("chnCd", chnCd);
        String insCompId = request.getParameter("insCompId");
        mav.addObject("insCompId", insCompId);

        String id = request.getParameter("id");
        GetByIdRequest req= new GetByIdRequest();
        req.setId(Long.valueOf(id));
        ResponseData data = this.insCompChnPollService.selectInsCompChnPolById(req);
        InsCompChnPolVO insCompChnPolVO = new InsCompChnPolVO();
        BeanUtils.copyProperties(data.getData(),insCompChnPolVO);
        mav.addObject("insCompChnPolVO", insCompChnPolVO);
        return mav;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsCompChnPolList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        cn.fl.insurance.condition.InsCompChnPolQueryCondition qc = new cn.fl.insurance.condition.InsCompChnPolQueryCondition();
        //设置查询条件？
        String insCompId = request.getParameter("insCompId");
        if (StringUtils.isNotEmpty(insCompId)) {
            qc.setInsCompId(Long.valueOf(insCompId));
        } else {
            return null;
        }
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        qc.setUsrId(CurrentThreadContext.getCurrentUserId());
        qc.setCrtUsrId(CurrentThreadContext.getCurrentUserId());

        page.setCondition(qc);
//        List<InsCompChnPolVO> insCompChnPolVOList = new ArrayList<>();
        BaseLogUtils.info(logger, "initInsCompChnPolList", "初始化InsCompChnPol列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.insCompChnPolService.searchListPage(page);
        if (CollectionUtils.isEmpty(pager.getResultList())){
            return new ListPageVO<InsCompChnPolVO>(new ArrayList<>(), 0);
        }
        List<InsCompChnPolVO> list = (List<InsCompChnPolVO>) pager.getResultList();
        ListPageVO<InsCompChnPolVO> listPage = new ListPageVO<InsCompChnPolVO>(list, pager.getTotalCount());
        /*ResponseData<InsCompChnPolResponse> data = insCompChnPollService.searchListPageByCondition(page.getCurrentPage(), page.getEveryPage(), qc);
        if (data.getCode().equals(ResponseData.FAIL_CODE) || null == data.getData()){
            throw new BaseException("查询渠道政策列表失败！");
        }
        List<InsCompChnPolDTO> insCompChnPolDTOList = data.getData().getInsCompChnPolDTOList();
        for(InsCompChnPolDTO insCompChnPolDTO :insCompChnPolDTOList){
            InsCompChnPolVO ins = new InsCompChnPolVO();
            BeanUtils.copyProperties(insCompChnPolDTO, ins);
            insCompChnPolVOList.add(ins);
        }
        ListPageVO<InsCompChnPolVO> listPage = new ListPageVO<InsCompChnPolVO>(insCompChnPolVOList, data.getData().getTotalCount());*/
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeInsCompChnPolByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsCompChnPolByIds", "删除InsCompChnPol数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            DeleteByIdsRequest req = new DeleteByIdsRequest();
            req.setIds(idsList);
            ResponseData data = insCompChnPollService.deleteByIds(req);
            if (!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeInsCompChnPolByIds", "删除InsCompChnPol数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeInsCompChnPolByIds", "删除InsCompChnPol数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeInsCompChnPolByIds", "删除InsCompChnPol数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeInsCompChnPolByIds", "删除InsCompChnPol数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getInsCompChnPolById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getInsCompChnPolById", "获取InsCompChnPol数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            GetByIdRequest req = new GetByIdRequest();
            req.setId(Long.valueOf(id));
            ResponseData data = insCompChnPollService.selectInsCompChnPolById(req);
            InsCompChnPolVO vo = new InsCompChnPolVO();
            BeanUtils.copyProperties(data.getData(),vo);
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getInsCompChnPolById", "获取InsCompChnPol数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getInsCompChnPolById", "获取InsCompChnPol数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getInsCompChnPolById", "获取InsCompChnPol数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getInsCompChnPolById", "获取InsCompChnPol数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 根据保险产品类型、保险种类字典列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getInsDictList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getInsDictList(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        List<KeyValueVO> insTypCdList = this.insCompChnPolService.searchInsTypCdList();
        List<KeyValueVO> prdTypCdList = this.insCompChnPolService.searchPrdTypCdList();
        List<KeyValueVO> rebNatCdList = this.insCompChnPolService.searchRebNatCdList();
        Map<String, List<KeyValueVO>> map = new HashMap<>();
        map.put("insTypCdList", insTypCdList);
        map.put("prdTypCdList", prdTypCdList);
        map.put("rebNatCdList", rebNatCdList);
        result.setData(map);
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addInsCompChnPol(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        InsCompChnPolVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForInsCompChnPol(request);//获取参数

            AddCompChnPolRequest req = new AddCompChnPolRequest();
            InsCompChnPolDTO dto = new InsCompChnPolDTO();
            BeanUtils.copyProperties(entity,dto);
            req.setDto(dto);
            ResponseData data = insCompChnPollService.addInsCompChnPol(req);
            result.setData(dto.getId());
            BaseLogUtils.info(logger, "addInsCompChnPol", "新增InsCompChnPol数据成功,ID:" + dto.getId() + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addInsCompChnPol", "新增InsCompChnPol数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addInsCompChnPol", "新增InsCompChnPol数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/addCompChnPol.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object batchAddCompChnPol(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        BaseLogUtils.newLogger("批量新增渠道政策，request:{}", JSON.toJSONString(request.getParameterMap())).info();
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存成功");
        String insCompId = request.getParameter("insCompId");
        List<InsCompChnPolVO> entityList = null;//获取参数
        try {
            if (StringUtils.isEmpty(insCompId)){
                throw new BaseException("保险支公司ID不能为空！");
            }
            entityList = this.getRequestParam(request);//获取参数
            ModifyAndAddInsCompPolListRequest req = new ModifyAndAddInsCompPolListRequest();
            List<InsCompChnPolDTO> insCompChnPolDTOList = new ArrayList<>();
            for(InsCompChnPolVO insCompChnPolVO :entityList){
                InsCompChnPolDTO ins = new InsCompChnPolDTO();
                BeanUtils.copyProperties(insCompChnPolVO, ins);
                insCompChnPolDTOList.add(ins);
            }
            req.setDtoList(insCompChnPolDTOList);
            req.setInsCompId(Long.valueOf(insCompId));
            req.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            BaseLogUtils.newLogger("批量新增渠道政策，req:{}", JSON.toJSONString(req)).info();
            ResponseData data = insCompChnPollService.batchAddChnPol(req);
            BaseLogUtils.newLogger("批量新增渠道政策，data:{}", JSON.toJSONString(data)).info();
            if (data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())) {
                BaseLogUtils.info(logger, "batchAddCompChnPol", "批量新增InsCompChnPol数据成功,.DATA:" + JSONObject.toJSONString(entityList), CurrentThreadContext.getCurrentUserName());
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "batchAddCompChnPol", "批量新增InsCompChnPol数据失败.DATA:" + JSONObject.toJSONString(entityList) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "batchAddCompChnPol", "批量新增InsCompChnPol数据失败,系统错误.DATA:" + JSONObject.toJSONString(entityList) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyInsCompChnPol(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        InsCompChnPolVO entity = null;
        try {
            entity = this.getRequestParamForInsCompChnPol(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyInsCompChnPol", "修改InsCompChnPol信息,主键参数为空！.ID:" + entity.getId(), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            ModifyCompChnPolRequest req = new ModifyCompChnPolRequest();
            InsCompChnPolDTO dto = new InsCompChnPolDTO();
            BeanUtils.copyProperties(entity,dto);
            req.setDto(dto);
            ResponseData data = insCompChnPollService.modifyInsCompChnPol(req);
            if (!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyInsCompChnPol", "修改InsCompChnPol数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyInsCompChnPol", "修改InsCompChnPol数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyInsCompChnPol", "修改InsCompChnPol数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyInsCompChnPol", "修改InsCompChnPol数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private InsCompChnPolVO getRequestParamForInsCompChnPol(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String insCompId = request.getParameter("insCompId");
        String prdTypCd = request.getParameter("prdTypCd");
        String insTypCd = request.getParameter("insTypCd");
        String rebPct = request.getParameter("rebPct");
        String rebNatCd = request.getParameter("rebNatCd");
        String rebAmt = request.getParameter("rebAmt");
        String rebDt = request.getParameter("rebDt");
        String prInstId = request.getParameter("prInstId");
        //String audStsCd = request.getParameter("audStsCd");
        String prjPrdId = request.getParameter("prjPrdId");
        String chnCd = request.getParameter("chnCd");
        String disRat = request.getParameter("disRat");
        String fstDisRat = request.getParameter("fstDisRat");
        String renewDisRat = request.getParameter("renewDisRat");


        //验证参数并赋值
        InsCompChnPolVO entity = new InsCompChnPolVO();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
        }

        if (StringUtils.isBlank(insCompId)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险支公司不能为空.");
        }
        entity.setInsCompId(Long.valueOf(insCompId));
        if (StringUtils.isBlank(prdTypCd)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "产品类型不能为空.");
        }
        entity.setPrdTypCd(prdTypCd);
        if (StringUtils.isBlank(insTypCd)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险种类不能为空.");
        }
        entity.setInsTypCd(insTypCd);
        if (StringUtils.isNotBlank(chnCd) && InsuranceConstant.CODE_INS_COMP_CHN_CD_1.equals(chnCd)) {
            if (StringUtils.isBlank(rebPct)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "返利比例不能为空.");
            }
            if (StringUtils.isNotBlank(disRat)) {
                entity.setDisRat(Integer.valueOf(disRat));
            }
            if (StringUtils.isNotBlank(fstDisRat)) {
                entity.setFstDisRat(fstDisRat.trim());
            }
            if (StringUtils.isNotBlank(renewDisRat)) {
                entity.setRenewDisRat(renewDisRat.trim());
            }
            entity.setRebPct(Double.valueOf(rebPct));
            entity.setAudStsCd("30");
        } else if (StringUtils.isNotBlank(chnCd) && InsuranceConstant.CODE_INS_COMP_CHN_CD_2.equals(chnCd)) {
            if (StringUtils.isBlank(rebNatCd)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "返利性质不能为空.");
            }
            if (StringUtils.isBlank(rebAmt)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "返利金额不能为空.");
            }
            if (StringUtils.isBlank(rebDt)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "返利时间不能为空.");
            }
            if (StringUtils.isBlank(prjPrdId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "项目产品不能为空.");
            }
            entity.setRebNatCd(rebNatCd);
            entity.setRebAmt(Long.valueOf(rebAmt));
            entity.setRebDt(DateUtils.formatStringToDate(rebDt, DateUtils.YYYY_MM_DD));
            entity.setPrjPrdId(Long.valueOf(prjPrdId));
            entity.setPrInstId(prInstId);
            entity.setAudStsCd("20");
        }

        Date tm = new Date();
        entity.setCrtTm(tm);
        entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        entity.setMdfTm(tm);
        entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        return entity;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private List<InsCompChnPolVO> getRequestParam(HttpServletRequest request) throws BaseException {
        List<InsCompChnPolVO> list = null;
        //获取参数
        String chnCd = request.getParameter("chnCd");
        String insCompId = request.getParameter("insCompId");
        String prInstId = request.getParameter("prInstId");
        if (StringUtils.isBlank(insCompId)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险支公司不能为空.");
        }
        if (StringUtils.isBlank(chnCd)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险渠道不能为空.");
        }
        String data = request.getParameter("data");
        list = JSON.parseArray(data, InsCompChnPolVO.class);
        if (list != null && list.size() > 0) {
            String temp = "";
            if ("1".equals(chnCd)) {//我司渠道政策
                StringBuffer insPrdTyp = new StringBuffer(";");
                for (InsCompChnPolVO vo : list) {
                    vo.setChnCd("1");
                    if (StringUtils.isBlank(vo.getPrdTypCd())) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "产品类型不能为空.");
                    }
                    if (StringUtils.isBlank(vo.getInsTypCd())) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "保险种类不能为空.");
                    }
                    if (vo.getRebPct() == null) {//返利比例
                        vo.setRebPct(0d);
                    }
                    if (vo.getDisRat() == null) {//折扣系数
                        vo.setDisRat(0);
                    }
                    temp = vo.getPrdTypCd() + "@" + vo.getInsTypCd() + ";";
                    if (insPrdTyp.toString().contains(";" + temp)) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "渠道政策重复.");
                    }
                    insPrdTyp.append(temp);
                    vo.setInsCompId(Long.valueOf(insCompId));
                    vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                    vo.setAudStsCd("30");//审核状态默认通过
                    vo.setRebAmt(0L);//返利金额
                }
            } else {//非我司渠道政策
                for (InsCompChnPolVO vo : list) {
                    vo.setChnCd("2");
                    if (vo.getPrjPrdId() == null) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "项目产品不能为空.");
                    }
                    if (StringUtils.isBlank(vo.getPaySchNo())) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "支付表编号不能为空.");
                    }
                    if (StringUtils.isBlank(vo.getPrdTypCd())) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "产品类型不能为空.");
                    }
                    if (StringUtils.isBlank(vo.getInsTypCd())) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "使用控制不能为空.");
                    }
                    if (StringUtils.isBlank(vo.getRebNatCd())) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "返利性质不能为空.");
                    }
                    if (vo.getRebDt() == null) {
                        throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "返利时间不能为空.");
                    } else {
                        vo.setRebDt(DateUtils.formatDate(vo.getRebDt(), DateUtils.YYYY_MM_DD));
                    }
                    if (vo.getRebAmtDou() == null) {
                        vo.setRebAmt(0L);
                    } else {
                        vo.setRebAmt(DecimalUtils.convertYuanToFen(vo.getRebAmtDou()));
                    }

                    vo.setInsCompId(Long.valueOf(insCompId));
                    vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                    vo.setAudStsCd("20");//审核状态默认审核中
                    vo.setRebPct(0.0);//返利比例
                    vo.setDisRat(0);//折扣系数
                    vo.setPrInstId(prInstId);
                }
            }
        }
        return list;
    }


    /**
     * 保险支公司一次性渠道政策申请
     */
    @RequestMapping(value = "/chnPolApply.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO chnPolApply(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "流程发起成功");
        List<InsCompChnPolVO> entityList = null;//获取参数
        try {
            entityList = this.getRequestParam(request);//获取参数
            result = this.insCompChnPolService.addChnPolApply(entityList);
            BaseLogUtils.info(logger,"chnPolApply","保险支公司一次性渠道政策申请==>"+JSON.toJSONString(result));
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "chnPolApply", "保险支公司一次性渠道政策申请失败.DATA:" + JSONObject.toJSONString(entityList) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "chnPolApply", "保险支公司一次性渠道政策申请失败,系统错误.DATA:" + JSONObject.toJSONString(entityList) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }
}

